# -*- encoding:utf-8 -*-
"""
Convert Ecilpse color scheme xml file into plain text
convert Hex color string into r,g,b
"""

import xml.etree.ElementTree as ET
import Hex2RGB
import csv
from pprint import pprint

def convert_xml(file):
    tree = ET.parse(file)
    root = tree.getroot()
    assert(root.tag=='colorTheme')
    name = root.attrib['name']
    adict = dict()
    for child in root:
        tag = child.tag
        color = child.attrib['color']
        rgb = Hex2RGB.hex2rgb(color)
        adict[tag] = rgb
    return name, adict

def write_csv(name, colordict):
    with open(name+'.csv', 'w', newline='') as csvfile:
        colorwriter = csv.writer(csvfile,dialect='excel')
        for tag in sorted(colordict.keys()):
            r,g,b = colordict[tag]
            colorwriter.writerow([tag, r, g, b])

def write_html(name, colordict):
    with open(name+'.html', 'w') as htmlfile:
        html_head = "<html><body><table align='center'><tr><td colspan='4' align='middle'> %s </td></tr><tr><td>Ex</td><td>Tag</td><td>Red__</td><td>Green</td><td>Blue_</td>" \
                    % name
        html_tail = "</table></body></html>"
        html = [html_head]
        for tag in sorted(colordict.keys()):
            r, g, b = colordict[tag]
            html.append('<tr><td bgcolor="%s"></td><td>%s</td> <td>%d</td> <td>%d</td> <td>%d</td></tr> '
                             % (Hex2RGB.rgb2hex(r,g,b), tag, r, g, b))
        html.append(html_tail)
        htmlfile.writelines(html)

if __name__ == '__main__':
    name, colors = convert_xml('theme-14105.xml')
    write_html(name, colors)
    pprint(colors)

